package com.juku2024.juku.adapter

import android.graphics.Color
import android.text.Spannable
import android.text.SpannableString
import android.text.TextUtils
import android.text.style.ForegroundColorSpan
import android.widget.ImageView
import android.widget.ProgressBar
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.juku2024.juku.R
import com.juku2024.juku.tools.*
import com.wanban.download.WBDownloadUtils
import com.wanban.download.db.DownloadEntity
import com.wanban.download.model.Status
import java.text.DecimalFormat

/**
 * Created by fq on 2017/6/7.
 */
class DlRunningAdapter(downloads: ArrayList<DownloadEntity>) :
    BaseQuickAdapter<DownloadEntity, BaseViewHolder>(R.layout.item_dl_running, downloads) {

    var isNetError = false
    var isShowCheck = false
    private val decimalPercentFormat by lazy { DecimalFormat("0.00%") }

    init {
        addChildClickViewIds(R.id.edit_button_fl)
    }

    override fun convert(holder: BaseViewHolder, item: DownloadEntity) {
        val name = if (item.category == Constants.VIDEO_CATEGORY_ALBUM) {
            String.format("%s  第%s集", item.videoName, item.episodeName)
        } else if (item.category == Constants.VIDEO_CATEGORY_VARIFY){
            if (item.episodeName?.endsWith("期") == true) {
                String.format("%s  %s", item.videoName, item.episodeName)
            } else {
                String.format("%s  %s期", item.videoName, item.episodeName)
            }
        } else {
            String.format("%s  %s", item.videoName, item.episodeName)
        }
        holder.setText(R.id.tvDlName, name)
            .setText(R.id.tvDlSize, AppUtils.getStoreSize(item.contentLength))

        if (isNetError || !NetworkUtils.isNetworkConnected()) {
            holder.setText(R.id.tvDlSpeed, AppUtils.getString(R.string.error_net)).setTextColorRes(R.id.tvDlSpeed, R.color.purple_200)
        } else {
            initDlState(item, holder)
        }

        val progressBar = holder.getView<ProgressBar>(R.id.progressBar)
        progressBar.max = 100000
        progressBar.progress = if (item.percent < 0) {
            0
        } else {
            (item.percent * 1000).toInt()
        }

        val imageView = holder.getView<ImageView>(R.id.iv_dl)
        loadCoverImage(imageView, item)

        val resId = if (item.isSelected) {
            R.drawable.ic_checked
        } else {
            R.drawable.ic_check_normal
        }
        holder.setBackgroundResource(R.id.viewCheck, resId)
            .setGone(R.id.viewCheck, !isShowCheck)
    }

    private fun loadCoverImage(iv: ImageView, downloadBean: DownloadEntity) {
        ImageUtils.loadImageH(iv, downloadBean.coverImagePath)
    }

    private fun checkPhoneNet(holder: BaseViewHolder): Boolean {
        if (NetworkUtils.isNetworkTypeMobile() && WBDownloadUtils.isDownloadOnlyWifi()) {
            holder.setText(R.id.tvDlSpeed, AppUtils.getString(R.string.dl_no_mobile_download))
                .setTextColor(R.id.tvDlSpeed, Color.parseColor("#E00000"))
        } else {
            return true
        }
        return false
    }

    private fun initDlState(downloadEntity: DownloadEntity, holder: BaseViewHolder) {
         when (downloadEntity.state) {
            Status.PREPARE -> {
                if (checkPhoneNet(holder)) {
                    holder.setText(R.id.tvDlSpeed, AppUtils.getString(R.string.dl_connecting))
                        .setTextColorRes(R.id.tvDlSpeed, R.color.color_text_dark)
                }
            }
             Status.DOWNLOADING, Status.START -> {
                if (checkPhoneNet(holder)) {
                    holder.setTextColorRes(R.id.tvDlSpeed, R.color.color_text_dark)
                    var percent = downloadEntity.percent / 100f
                    if (percent < 0f) {
                        percent = 0f
                    }
                    val percentStr = decimalPercentFormat.format(percent) ?: ""
                    //校正一下速度出现-1的情况
                    val speed = if (downloadEntity.speed < 0) {
                        0
                    } else {
                        downloadEntity.speed
                    }
                    //优化显示效果，youTube下载速度速度为0的问题的优化
                    val text = if (speed <= 0L) {
                        String.format("%s/s   %s", "0KB", percentStr)
                    } else {
                        String.format("%s/s   %s", AppUtils.getStoreSize(speed), percentStr)
                    }
                    holder.setText(R.id.tvDlSpeed, text)
                }
            }
             Status.STOP -> {
                if (checkPhoneNet(holder)) {
                    holder.setText(R.id.tvDlSpeed, AppUtils.getString(R.string.dl_pause))
                        .setTextColorRes(R.id.tvDlSpeed, R.color.color_text_light)
                }
            }
             Status.ERROR -> {
                if (checkPhoneNet(holder)) {
                    holder.setText(R.id.tvDlSpeed, downloadEntity.errorMsg?:AppUtils.getString(R.string.dl_error_detail))
                        .setTextColorRes(R.id.tvDlSpeed, R.color.color_text_light)
                }
            }
            else -> {
                if (checkPhoneNet(holder)) {
                    holder.setText(R.id.tvDlSpeed, getColorSpannableString(
                        AppUtils.getString(R.string.dl_wait_for),
                        AppUtils.getColor(R.color.color_text_dark)
                    )
                    )
                }
            }
        }
    }

    private fun getColorSpannableString(resource: String, color: Int): SpannableString? {
        if (TextUtils.isEmpty(resource)) return null
        val spannableString =  SpannableString(resource)
        val span =  ForegroundColorSpan(color)
        spannableString.setSpan(span, 0, 4, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
        return spannableString
    }
}